<!-- sign_up -->
<template>
  <div class="container a-container" id="a-container">
    <form class="form" id="a-form" @submit.prevent="handleRegister">
      <h2 class="form_title title">Create Account</h2>
      <div class="form__icons">
        <img class="form__icon" src=" " />
        <img class="form__icon" src=" " />
        <img class="form__icon" src=" " />
      </div>
      <span class="form__span">or use email for registration</span>
      <input class="form__input" type="text" placeholder="用户名" v-model="registerForm.username" />
      <input class="form__input" type="password" placeholder="密码" v-model="registerForm.password" />
      <input class="form__input" type="password" placeholder="确认密码" v-model="registerForm.confirmPassword" />
      <button class="form__button button submit" type="submit">SIGN UP</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus';

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const handleRegister = async () => {
  // 验证密码
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致');
    return;
  }

  try {
    const response = await fetch('http://localhost:3456/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: registerForm.value.username,
        password: registerForm.value.password
      })
    });

    const data = await response.json();
    
    if (response.ok) {
      // 注册成功
      ElMessage.success('注册成功');
      // 清空表单
      registerForm.value = {
        username: '',
        password: '',
        confirmPassword: ''
      };
    } else {
      // 注册失败
      ElMessage.error(data.message || '注册失败');
    }
  } catch (error) {
    console.error('注册错误:', error);
    ElMessage.error('注册失败，请稍后重试');
  }
};
</script>

<style scoped lang="scss">
@import './login.scss';
</style>